import React, { useCallback, useState } from "react";

// 父组件
export default function StudyUseCallback() {
	const [count, setCount] = useState(0);

	// 使用 useCallback 记忆化函数
	const handleClick = useCallback(() => {
		console.log("Button clicked");
	}, []); // 空依赖项表示该函数只在初次渲染时创建

	// const handleClick = () => {
	//     console.log('Button clicked');
	// }

	return (
		<div>
			<h2>5. Study useCallback</h2>
			<p>Count: {count}</p>
			<button onClick={() => setCount(count + 1)}>Increment Count</button>

			{/* 将回调函数传递给子组件 */}
			<ChildComponent onClick={handleClick} />
		</div>
	);
}

// 子组件类型定义
type ChildComponentProps = {
	onClick: () => void;
};

// 子组件
const ChildComponent: React.FC<ChildComponentProps> = React.memo(({ onClick }) => {
		console.log("Child component rendered");
		return <button onClick={onClick}>Click Me</button>;
	}
);
